<template>
	<view>
		<uni-nav-bar fixed :status-bar="true" @clickLeft="goBack">
			<view slot="left" class="navbar-icon left-icon icon-font">&#xe612;</view>
			<input
				class="search-input"
				@confirm="toSearch"
				@input="inputSearch"
				@focus="updateShowSuggest"
				@blur="updateShowSuggest"
				v-model="keyword"
				focus
				confirm-type="search"
				placeholder="搜索"
			/>

			<!-- #ifdef APP-PLUS || H5 -->
			<view slot="right" class="navbar-icon icon-font">&#xe600;</view>
			<!-- #endif -->
		</uni-nav-bar>

		<!-- 滚动区域 -->
		<scroll-view v-show="!isShowSearchResult" class="page-content" scroll-y="true">
			<template v-if="historyList.length > 0">
				<view class="history flex-box">
					<view class="txt">历史记录</view>
					<view class="icon-font" @tap="clearHistory">&#xe6dc;</view>
				</view>

				<scroll-view class="history-list scroll-view" scroll-x :show-scrollbar="false">
					<view class="history-item" v-for="(item, index) in historyList" :key="index" @tap="search(item)">
						<view class="desc">{{ item }}</view>
					</view>
				</scroll-view>
			</template>

			<view class="hot">
				<view class="title">热搜榜</view>
				<view class="hot-list">
					<view class="hot-item flex-box" v-for="(item, index) in hotList" :key="index" @tap="search(item.searchWord)">
						<view class="num" :class="{ red: index < 3 }">{{ index + 1 }}</view>
						<view class="flex-item">
							<view class="word flex-box">
								<view class="name flex-box">
									<view class="txt" :class="{ bold: index < 3 }">{{ item.searchWord }}</view>
									<image class="icon" :src="item.iconUrl" mode="scaleToFill"></image>
								</view>
								<view class="score">{{ item.score }}</view>
							</view>
							<view class="content">{{ item.content }}</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<view v-show="isShowSearchResult" class="page-content" style="position: static">
			<ms-tabs v-if="isShowSearchResult" :list="tabList" v-model="active" itemColor="red" lineColor="red"></ms-tabs>
			<mescroll-body @init="mescrollInit" :down="downOption" @up="upCallback" :up="upOption">
				<view class="song-list">
					<view class="song-item flex-box" v-for="(item, index) in songList" :key="index">
						<view class="song-theme" @tap="playSong(item)">
							<!-- #ifdef MP-WEIXIN -->
							<view class="song-name ellipsis">
								<text>{{item.name}}</text>
								<text class="alias" v-if="item.alias.length > 0">
									<text>（</text>
									<text>{{item.alias[0]}}</text>
									<text>)</text>
								</text>
							</view>
							<view class="singer">
								<block v-for="(artist, index) in item.artists" :key="index">
									<text>{{artist.name}}</text>
									<block v-if="index !== item.artists.length - 1">/</block>
								</block>
								<text class="link">-</text>
								<text>{{item.album.name}}</text>
							</view>
							<view class="singer" v-if="item.alias.length > 0">{{item.alias[0]}}</view>
							<!-- #endif -->
							
							<!-- #ifndef MP-WEIXIN -->
							<view class="song-name ellipsis">
								<text v-html="keywordHighlights(item.name)"></text>
								<text class="alias" v-if="item.alias.length > 0">
									<text>（</text>
									<text v-html="keywordHighlights(item.alias[0])"></text>
									<text>)</text>
								</text>
							</view>
							<view class="singer">
								<block v-for="(artist, index) in item.artists" :key="index">
									<text v-html="keywordHighlights(artist.name)"></text>
									<block v-if="index !== item.artists.length - 1">/</block>
								</block>
								<text class="link">-</text>
								<text v-html="keywordHighlights(item.album.name)"></text>
							</view>
							<view class="singer" v-if="item.alias.length > 0" v-html="keywordHighlights(item.alias[0])"></view>
							<!-- #endif -->
						</view>

						<view class="more icon-font">&#xe700;</view>
					</view>
				</view>
			</mescroll-body>
		</view>

		<view class="keyword-list" v-if="suggestList.length > 0 && isShowSuggest">
			<view class="keyword-item search-keyword">
				<view>搜索“{{ keyword }}”</view>
			</view>
			<view class="keyword-item flex-box" v-for="(itme, index) in suggestList" :key="index" @tap="search(itme.keyword)">
				<view class="icon-font">&#xe714;</view>
				<view>{{ itme.keyword }}</view>
			</view>
		</view>
		
		<confirm ref="confirm"></confirm>
	</view>
</template>

<script>
import { listHotSearch, listSearchSuggest, searchSong } from '@/api/index.js';
import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar/uni-nav-bar.vue';
import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js';
import msTabs from '@/components/ms-tabs/ms-tabs.vue';
import confirm from '@/components/message/confirm.vue';

// 防抖
function debounce(fn, wait = 300) {
	var timeout = null;
	return function() {
		if (timeout !== null) {
			clearTimeout(timeout);
		}
		timeout = setTimeout(fn, wait);
	};
}
var that = null;
export default {
	mixins: [MescrollMixin],
	data() {
		return {
			mescroll: '',
			downOption: {
				use: false
			},
			upOption: {
				auto: false, // 是否在初始化完毕之后自动执行上拉加载的回调; 默认true
				page: {
					num: 1, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
					size: 10 // 每页数据的数量,默认10
				}
			},
			isShowSuggest: false,
			isShowSearchResult: false,
			keyword: '',
			historyList: [],
			hotList: [],
			suggestList: [],
			songList: [],
			active: 0,
			tabList: [
				{
					title: '综合'
				},
				{
					title: '单曲'
				},
				{
					title: '云村'
				},
				{
					title: '视频'
				},
				{
					title: '歌手'
				},
				{
					title: '专辑'
				},
				{
					title: '歌单'
				},
				{
					title: '用户'
				}
			]
		};
	},
	onLoad() {
		that = this;
		this.getHistory();
		this.getHotList();
	},
	onBackPress(options) {
		if (this.isShowSearchResult) {
			this.isShowSearchResult = false;
			return true;
		}
		return false;
	},
	watch: {
		active() {
			this.search();
		}
	},
	methods: {
		goBack() {
			uni.navigateBack();
		},

		updateShowSuggest() {
			setTimeout(() => {
				this.isShowSuggest = !this.isShowSuggest;
				if (this.isShowSuggest) {
					this.inputSearch();
				}
			}, 50);
		},

		toSearch(obj) {
			if (obj.detail.value) {
				this.search(obj.detail.value);
			}
		},

		search(val) {
			// 搜索歌曲
			if (val) {
				this.keyword = val;
			}
			this.addHistory(this.keyword);
			this.suggestList = [];

			this.isShowSearchResult = true;
			this.songList = [];
			this._searchSong(1);
		},

		// mescroll 初始化
		mescrollInit(mescroll) {
			this.mescroll = mescroll;
		},
		/*上拉加载的回调*/
		upCallback(page) {
			this._searchSong(page.num);
		},

		_searchSong(page) {
			let params = {};
			params.keywords = this.keyword;
			params.limit = 30;
			params.offset = (page - 1) * params.limit;

			searchSong(params).then(res => {
				let length = 0;
				if (res.result.songs) {
					this.songList = this.songList.concat(res.result.songs);
					length = res.result.songs.length;
				}
				this.mescroll.endSuccess(length);
			});
		},

		inputSearch: debounce(() => {
			// 未搜索或者写入空格的情况下不显示搜索建议
			if (!that.keyword.trim().length) {
				that.suggestList = [];
				return false;
			}
			// 请求后台数据
			listSearchSuggest(that.keyword).then(res => {
				that.suggestList = res.result.allMatch;
			});
		}),

		addHistory(value) {
			if (value.length == 0) {
				// 空字符不添加
				return false;
			}

			const tempIndex = this.historyList.indexOf(value);
			if (tempIndex !== -1) {
				// 如果存在相同的删除旧的
				this.historyList.splice(tempIndex, 1);
			}

			this.historyList.unshift(value);
			uni.setStorageSync('search-history', this.historyList);
		},

		clearHistory() {
			// 清空历史记录
			this.$refs.confirm.open({
				content: '确定要清空全部历史记录?',
				confirm: () => {
					this.historyList = [];
					uni.clearStorageSync('search-history');
				}
			})
	
		},

		getHistory() {
			let value = uni.getStorageSync('search-history');
			if (value) {
				this.historyList = value;
			}
		},

		getHotList() {
			// 获取热搜
			if (this.hotList.length > 0) {
				return;
			}

			listHotSearch().then(res => {
				this.hotList = res.data;
			});
		},

		playSong(item) {
			// 设置播放列表
			let historyPlaySongList = uni.getStorageSync('uni-history-play-song');
			if (!historyPlaySongList) {
				historyPlaySongList = [];
			}
			
			let song = {};
			song.id = item.id;
			song.name = item.name;
			if (item.alias.length > 0) {
				song.alia = item.alias[0];
			}
			song.alName = item.album.name;
			song.singer = item.artists
				.map(art => {
					return art.name;
				})
				.join('/');
				
			historyPlaySongList = historyPlaySongList.filter(item => {
				return item.id != song.id;
			})
			historyPlaySongList.push(song);
			
			uni.setStorageSync('uni-history-play-song', historyPlaySongList);
			let payload = {
				isSearch: true,
				list: historyPlaySongList,
				curSong: song
			};
			// 保存播放列表到store
			this.$store.commit('SET_PLAY_LIST', payload);

			uni.navigateTo({
				url: '/pages/subpages/index/play'
			});
		},

		keywordHighlights(value) {
			return value.replace(this.keyword, "<text style='color:#6c8eb8'>" + this.keyword + '</text>');
		}
	},
	components: {
		uniNavBar,
		msTabs,
		confirm
	}
};
</script>

<style lang="scss" scoped>
.left-icon {
	padding-left: 20rpx;
}

.page-content {
	width: 700rpx;
	margin: 0 auto;
	bottom: 0;
	background-color: #fff;
}

.search-input {
	width: 530rpx;
	height: 65rpx;
	line-height: 65rpx;
	color: #333;
	justify-content: center;
	border-bottom: 1rpx solid #e6e6e6;
}

.history {
	margin-top: 30rpx;
	justify-content: space-between;
	font-size: 30rpx;
	line-height: 30rpx;
	.txt {
		font-weight: 600;
	}
	.icon-font {
		font-size: 40rpx;
	}
}

.history-list {
	margin-top: 30rpx;
	white-space: nowrap;
	.history-item {
		display: inline-block;
		height: 50rpx;
		line-height: 50rpx;
		padding: 0 25rpx;
		margin-right: 20rpx;
		border-radius: 50rpx;
		color: #323232;
		background: #f8f8f8;
	}
}

.hot {
	margin-top: 50rpx;

	.title {
		font-size: 26rpx;
		font-weight: 600;
	}

	.hot-item {
		align-items: center;
		height: 120rpx;
	}

	.num {
		width: 30rpx;
		margin-right: 30rpx;
		text-align: center;
		color: #999;
	}

	.word {
		flex-wrap: nowrap;
		align-items: center;
		justify-content: space-between;
		height: 48rpx;
		line-height: 48rpx;
	}

	.name {
		align-items: center;
		flex-wrap: nowrap;
	}

	.txt {
		margin-right: 20rpx;
		color: #333;
		font-size: 32rpx;
		font-weight: 600;
	}

	.bold {
		font-weight: 700 !important;
	}

	.score {
		align-items: right;
		color: #ccc;
		justify-content: right;
		font-size: 24rpx;
	}

	.icon {
		width: 56rpx;
		height: 20rpx;
	}

	.content {
		color: #999;
		font-size: 24rpx;
	}

	.red {
		color: red;
	}
}

.song-list {
	width: 700rpx;
	margin: 20rpx, auto;

	.song-item {
		justify-content: space-between;
		margin-top: 50rpx;
	}

	.song-name {
		font-size: 30rpx;
		width: 650rpx;

		.alias {
			color: #9e9e9e;
		}
	}

	.singer {
		font-size: 22rpx;
		color: #666666;
	}

	.link {
		margin: 0 5rpx;
	}

	.more {
		color: #8a8a8a;
	}
}

/* 提示窗口 */
.uni-tip {
	/* #ifndef APP-NVUE */
	display: flex;
	flex-direction: column;
	/* #endif */
	padding: 15px;
	width: 300px;
	background-color: #fff;
	border-radius: 10px;
}

.uni-tip-title {
	margin-bottom: 10px;
	text-align: center;
	font-weight: bold;
	font-size: 16px;
	color: #333;
}

.uni-tip-content {
	/* padding: 15px;
	 */
	font-size: 14px;
	color: #666;
}

.uni-tip-group-button {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	margin-top: 20px;
}

.uni-tip-button {
	flex: 1;
	text-align: center;
	font-size: 14px;
	color: #3b4144;
}

.keyword-list {
	position: fixed;
	z-index: 10;
	top: calc(var(--status-bar-height) + 48px);
	left: 0;
	right: 0;
	margin: auto;
	width: 680rpx;
	background-color: #fff;
	box-shadow: 0 5rpx 15rpx #8f8f8f;
	border-radius: 5rpx;

	.search-keyword {
	}

	.keyword-item {
		line-height: 90rpx;
		height: 90rpx;
		font-size: 30rpx;
		color: #959595;
		border-bottom: 1rpx solid #e7e7e7;
		padding-left: 30rpx;

		&:first-child {
			color: #5a7b91;
		}
		&:last-child {
			border-bottom: none;
		}

		.icon-font {
			margin-right: 15rpx;
		}
	}
}
</style>
